import axios from 'axios'
import { Message, MessageBox, Notification } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'

const service = axios.create({
  baseURL: process.env.BASE_API, // api 的 base_url
  timeout: 5000 // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    if (store.getters.token) {
      // 让每个请求携带token-- ['token']为自定义key 请根据实际情况自行修改
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    console.log(error)
    Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /*
   * 当code返回如下情况则说明权限有问题，登出并返回到登录页
   **/
  response => {
    const res = response.data

    const { code, msg } = res

    if (code !== 0) {
      Message({
        message: msg,
        type: 'error',
        duration: 5 * 1000
      })
      // 判断是否过期
      if (code === 2) {
        MessageBox.confirm('身份认证已过期，可以取消继续留在该页面，或者重新登录', '确定登出', {
          confirmButtonText: '重新登录',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          store.dispatch('FedLogOut').then(() => {
            location.reload()
          })
        }).catch(() => {
          console.log('取消')
        })
      }
      if (code === 5) {
        Notification.error({
          title: '错误',
          message: msg,
          duration: 0
        })
      }
      return false
    } else {
      return response
    }
  },
  error => {
    Message({
      message: error.message,
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  }
)

export default service
